//
// Created by Semir on 2020/3/28.
//

#include <iostream>
#include <deque>
#include <cstring>

using namespace std;

const int MAX_LEN = 1010;

int n, m;
int maze[MAX_LEN][MAX_LEN];
int mark[MAX_LEN][MAX_LEN];
int dirX[4] = {0, -1, 0, 1};
int dirY[4] = {1, 0, -1, 0};
int elem_count[MAX_LEN * MAX_LEN];

void bfsMark(int x, int y, int block_num) {
    deque<int> queueX;
    deque<int> queueY;
    queueX.push_back(x);
    queueY.push_back(y);
    int count = 1;
    mark[x][y] = block_num;
    while (!queueX.empty() && !queueY.empty()) {
        x = queueX.front();
        y = queueY.front();
        queueX.pop_front();
        queueY.pop_front();
        for (int i = 0; i < 4; i++) {
            int dx = x + dirX[i];
            int dy = y + dirY[i];
            if (dx >= 1 && dx <= n && dy >= 1 && dy <= n && mark[dx][dy] < 0 && maze[x][y] != maze[dx][dy]) {
                mark[dx][dy] = block_num;
                queueX.push_back(dx);
                queueY.push_back(dy);
                count++;
            }
        }
    }
    elem_count[block_num] = count;
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            char ch;
            cin >> ch;
            maze[i][j] = ch == '0' ? 0 : 1;
        }
        memset(mark[i], -1, sizeof(mark[i]));
    }
    int block_num = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (mark[i][j] < 0) {
                bfsMark(i, j, block_num);
                block_num++;
            }
        }
    }
    for (int i = 0; i < m; i++) {
        int x, y;
        cin >> x >> y;
        cout << elem_count[mark[x][y]] << endl;
    }
    return 0;
}


